import { Drawer, message, Empty } from "antd";
import "./index.scss";
import { getUploadList } from "@/service/task";
import { useEffect, useState } from "react";
import emitter from "@/utils/eventEmitter";

const DownloadDrawer = (props) => {
  const onClose = () => {
    props.setOpen(false);
  };
  const [taskList, setTaskList] = useState([]);
  const getTaskList = async () => {
    const res = await getUploadList();
    if (res.status !== 200) message.error(res.msg);
    setTaskList(res.data);
  };

  const taskStautsMap = new Map([
    [1, "进行中"],
    [2, "成功"],
    [3, "失败"],
  ]);
  const colorMap = new Map([
    [1, "pedding"],
    [2, "success"],
    [3, "error"],
  ]);
  const TaskItem = () => {
    return taskList?.map((item) => (
      <div
        key={item._id}
        className={`download-item download-item-${colorMap.get(
          item.taskStatus
        )}`}
      >
        <div className="file-name">{item.taskName}</div>
        <div className="file-size">{`${(
          item.taskSize / Math.pow(1024, 2)
        ).toFixed(2)}MB`}</div>
        <div className="file-status">{taskStautsMap.get(item.taskStatus)}</div>
      </div>
    ));
  };



  useEffect(() => {
    emitter.on("refreshTaskList", getTaskList);
    emitter.on("showUploadDrawer", () => props.setOpen(true));

    let interval = null;
    
    if (props.isOpenUploadDLG) {
      getTaskList();
      interval = setInterval(() => {
        getTaskList();
      }, 1000);
    }

    // 清理函数
    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [props.isOpenUploadDLG]);
  return (
    <Drawer
      width={50}
      title="上传列表"
      mask={false}
      placement="bottom"
      open={props.isOpenUploadDLG}
      onClose={onClose}
    >
      {taskList?.length ? (
        <TaskItem></TaskItem>
      ) : (
        <Empty
          imageStyle={{
            marginTop: 40,
            height: 180,
          }}
          description={<span style={{ color: "gray" }}>没有任务噢</span>}
        ></Empty>
      )}
    </Drawer>
  );
};
export default DownloadDrawer;
